import React from 'react';
import { Message, Balloon, ConfigProvider } from '@teamix/ui';
import { Star, ButtonIcon } from '@alife/devops-ui';
import exceed from 'utils/apimap';
import intl from '../../../locale';

const { pathResource } = window.FORCE;
const { Tooltip } = Balloon;

export default class NavCollect extends React.Component {
  state = {
    starred: pathResource.isStar === 'true',
    description: null,
  };

  componentDidMount() {
    this.getDescription();
  }

  componentWillUnmount() {
    window.FORCE.pathResource.projectInfo = null;
  }

  getDescription = () => {
    setTimeout(() => {
      const { projectInfo } = window.FORCE.pathResource;
      if (!projectInfo) {
        this.getDescription();
        return;
      }
      this.setState({
        description: projectInfo.description,
      });
    }, 500);
  };

  doStar() {
    exceed
      .fetch({
        api: 'projects.star',
        params: { projectId: pathResource.id },
      })
      .then(() => {
        this.setState({
          starred: true,
        });

        Message.success({
          title: intl.get({
            id: 'code-assets.initNavigation.collect.CollectedSuccessfully',
            defaultMessage: '收藏成功',
          }),
        });
      })
      .fail(console.log);
  }

  doUnStar() {
    exceed
      .fetch({
        api: 'projects.unstar',
        params: { projectId: pathResource.id },
      })
      .then(() => {
        this.setState({
          starred: false,
        });

        Message.success({
          title: intl.get({
            id: 'code-assets.initNavigation.collect.Deleted',
            defaultMessage: '取消收藏成功',
          }),
        });
      })
      .fail(console.log);
  }

  render() {
    const { starred, description } = this.state;

    return (
      <ConfigProvider prefix="yx-">
        <span style={{ position: 'relative', top: '1px', display: 'flex', alignItems: 'center' }}>
          {!description ? null : (
            <Tooltip
              trigger={<ButtonIcon name="information-line" style={{ marginTop: '-2px' }} />}
              text={
                <div>
                  <div className="desc-popup-item-label">
                    {intl.get({
                      id: 'code-assets.initNavigation.collect.Description',
                      defaultMessage: '描述',
                    })}
                  </div>
                  {description}
                </div>
              }
            />
          )}
          <Star
            style={{ top: '-3px' }}
            starred={starred}
            onClick={() => {
              if (starred) {
                this.doUnStar();
              } else {
                this.doStar();
              }
            }}
          />
        </span>
      </ConfigProvider>
    );
  }
}
